package com.yuncheng.spcyApi.selectXzxkApi.api;

import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.entity.SpcyQyPzjbxx;
import com.yuncheng.spcyApi.entity.SpcyQyQygjryxx;
import com.yuncheng.spcyApi.entity.SpcyQyYlgyssj;
import com.yuncheng.spcyApi.selectXzxkApi.constant.XzXkConstant;
import com.yuncheng.spcyApi.selectXzxkApi.vo.XzspXzxdrXdrryVo;
import com.yuncheng.spcyApi.spcyService.SpcyQyInfoService;
import com.yuncheng.spcyApi.utils.LocalFileUploadUtils;
import com.yuncheng.spcyApi.utils.MyExcelUtils;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.vo.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hua
 */
@Api(tags = "审评查验-行政许可-企业相关接口")
@RestController
@RequestMapping("/api/spzx-spcy/xzxkqy")
public class SelectXzxkQyApi {

    private static final Logger log = LoggerFactory.getLogger(SelectXzxkQyApi.class);

    @Resource
    private XzspQyApi xzspQyApi;

    @Resource
    private SpcyQyInfoService spcyQyInfoService;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Log(title = "获取企业证件信息接口")
    @ApiOperation(value = "获取企业证件信息接口")
    @GetMapping(value = "queryQyzj")
    public HttpResult queryQyzj(@RequestParam(value = "tyshxydm",defaultValue = "") String tyshxydm,
                                @RequestParam(value = "fqyid",defaultValue = "") String fqyid
                                ) {
        if (StringUtils.isBlank(tyshxydm)){
            if (StringUtils.isNotBlank(fqyid)){
                tyshxydm = spcyQyInfoService.getTyshxydmById(fqyid);
            }else {
                return HttpResult.error("参数为空！");
            }
        }

        return xzspQyApi.selectQyzj(tyshxydm, "001002");
    }

    @Log(title = "获取证件详细信息接口")
    @ApiOperation(value = "获取证件详细信息接口")
    @GetMapping(value = "queryQyzjxx")
    public HttpResult queryQyzjxx(@RequestParam(value = "zjid",defaultValue = "") String zjid
    ) {
        if (StringUtils.isBlank(zjid)){
            return HttpResult.error("证件参数为空！");
        }
        return xzspQyApi.selectQyzjxx(zjid);
    }

    @Log(title = "获取日常检查信息接口")
    @ApiOperation(value = "获取日常检查信息接口")
    @GetMapping(value = "queryQyRcjc")
    public HttpResult queryQyRcjc(@RequestParam(value = "tyshxydm",defaultValue = "") String tyshxydm,
                                  @RequestParam(value = "fqyid",defaultValue = "") String fqyid
    ) {
        if (StringUtils.isBlank(tyshxydm)){
            if (StringUtils.isNotBlank(fqyid)){
                tyshxydm = spcyQyInfoService.getTyshxydmById(fqyid);
            }else {
                return HttpResult.error("参数为空！");
            }
        }

        return xzspQyApi.selectQyRcjc(tyshxydm);
    }

    @Log(title = "获取政务企业关键人员信息接口")
    @ApiOperation(value = "获取政务企业关键人员信息接口")
    @GetMapping(value = "queryQyRyxx")
    public HttpResult queryQyRyxx(@RequestParam(value = "tyshxydm",defaultValue = "") String tyshxydm,
                                  @RequestParam(value = "fqyid",defaultValue = "") String fqyid
    ) {
        if (StringUtils.isBlank(tyshxydm)){
            if (StringUtils.isNotBlank(fqyid)){
                tyshxydm = spcyQyInfoService.getTyshxydmById(fqyid);
            }else {
                return HttpResult.error("参数为空！");
            }
        }

        return HttpResultVo.HttpResultList(spcyQyInfoService.selectXzxdrIdByTyshxydm(tyshxydm));
    }

    @Log(title = "导出-政务企业关键人员信息接口")
    @ApiOperation(value = "导出-政务企业关键人员信息接口")
    @GetMapping("/exportQyRyxx")
    public void exportQyRyxx(@RequestParam(value = "tyshxydm",defaultValue = "") String tyshxydm,
                             @RequestParam(value = "fqyid",defaultValue = "") String fqyid,
                             HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(tyshxydm)){
            if (StringUtils.isNotBlank(fqyid)){
                tyshxydm = spcyQyInfoService.getTyshxydmById(fqyid);
            }else {
                response.setContentType("text/html");
                response.setCharacterEncoding("UTF-8");
                PrintWriter writer = response.getWriter();
                writer.println("必应参数为空！");
                writer.close(); // 不要忘记关闭PrintWriter
                return;
            }
        }

        try {
            String name = "exportQyRyxx";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<Object> list = new ArrayList<>(); // 导出的数据
            List<XzspXzxdrXdrryVo> dataList = spcyQyInfoService.selectXzxdrIdByTyshxydm(tyshxydm);
            for (XzspXzxdrXdrryVo e : dataList){
                list.add(e);
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.import_qy_zw_ryxx_XML, list, out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出-政务企业关键人员信息接口出错-{}",e.getMessage());
        }
    }

    @Log(title = "获取企业其他人员信息接口")
    @ApiOperation(value = "获取企业其他人员信息接口")
    @GetMapping(value = "queryQyQtRy")
    public HttpResult queryQyQtRy(@RequestParam(value = "fqyid",defaultValue = "") String fqyid
    ) {
        if (StringUtils.isBlank(fqyid)) {
            return HttpResult.error("参数为空！");
        }

        return HttpResultVo.HttpResultList(spcyQyInfoService.selectQyQtryxxByTyshxydm(fqyid));
    }

    @Log(title = "企业其他人员-添加")
    @ApiOperation(value = "企业其他人员-添加")
    @PostMapping(value = "addQyQtry")
    public HttpResult addQyQtry(@RequestBody SpcyQyQygjryxx gjryxx) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        if (StringUtils.isNotBlank(gjryxx.getId())){
            return spcyQyInfoService.updateQygjryxx((HashMap<String, String>) BeanUtils.describe(gjryxx));
        }

        gjryxx.setFrylx(XzXkConstant.RYFL_QTRY);
        if (StringUtils.isBlank(gjryxx.getFqyid())) {
            return HttpResult.error("参数为空！");
        }
        /*if (StringUtils.isBlank(gjryxx.getFqyid())){
            gjryxx.setFqyid(spcyQyInfoService.getCurrentQy());
        }*/
        return spcyQyInfoService.addQygjryxx(gjryxx, false);
    }

    @Log(title = "企业其他人员-更新")
    @ApiOperation(value = "企业其他人员-更新")
    @PutMapping(value = "updateQyQtry")
    public HttpResult updateQyQtry(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException {
        return spcyQyInfoService.updateQygjryxx(buffer);
    }

    @Log(title = "企业其他人员-删除")
    @ApiOperation(value = "企业其他人员-删除")
    @DeleteMapping(value = "deleteQyQtry")
    public HttpResult deleteQyQtry(String ids){
        return spcyQyInfoService.deleteQygjryxx(ids);
    }

    @Log(title = "导入-企业其他人员信息接口")
    @ApiOperation(value = "导入-企业其他人员信息接口")
    @PostMapping(value = "importQyQtRy")
    public HttpResult importQyQtRy(@RequestParam("file") MultipartFile file,
                                       @RequestParam(value = "fqyid",defaultValue = "") String fqyid){
        if (StringUtils.isBlank(fqyid)){
            return HttpResult.error("参数为空！");
        }

        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");
        }

        File fileUpload = localFileUploadUtils.uploadDempFile(file, fileName);
        // 获取导入的数据
        List<Map<String, Object>> dataMapList = null;
        try {
            dataMapList = myExcelUtils.paresExclToMapList(BusinessConstant.import_qy_ryxx_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入企业其他人员信息接口出错-{}",e.getMessage());
        }
        fileUpload.delete();
        boolean flag = spcyQyInfoService.importQyQtryxxByTyshxydm("", fqyid, dataMapList);
        if (!flag){
            return HttpResult.ok("导入失败！");
        }
        return HttpResult.ok("导入成功！");
    }

    @Log(title = "导出-企业其他人员信息接口")
    @ApiOperation(value = "导出-企业其他人员信息接口")
    @GetMapping("/exportQyQtRy")
    public void exportQyQtRy(@RequestParam(value = "fqyid",defaultValue = "") String fqyid,
                             HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(fqyid)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("参数为空！");
            writer.close(); // 不要忘记关闭PrintWriter
            return;
        }

        try {
            String name = "exportQyQtRy";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<Object> list = new ArrayList<>(); // 导出的数据
            List<SpcyQyQygjryxx> dataList = spcyQyInfoService.selectQyQtryxxByTyshxydm(fqyid);
            for (SpcyQyQygjryxx e : dataList){
                list.add(e);
            }

            myExcelUtils.outputListToExclFile(BusinessConstant.import_qy_ryxx_XML, list, out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出-企业其他人员信息接口出错-{}",e.getMessage());
        }
    }

    @Log(title = "下载企业其他人员信息接口-导入模板")
    @ApiOperation(value = "下载企业其他人员信息接口-导入模板")
    @GetMapping("/exporyQtryMb")
    public void exporyQtryMb(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("exporyQtryMb.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.import_qy_ryxx_XML, out);
        } catch (Exception e) {
            log.error("下载企业其他人员信息接口-导入模板-错误-{}",e.getMessage());
        }
    }

    @Log(title = "导入-企业供应商信息接口")
    @ApiOperation(value = "导入-企业供应商信息接口")
    @PostMapping(value = "importQyGysxx")
    public HttpResult importQyGysxx(@RequestParam("file") MultipartFile file,
                                   @RequestParam(value = "fqyid",defaultValue = "") String fqyid){
        if (StringUtils.isBlank(fqyid)){
            return HttpResult.error("参数为空！");
        }

        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");
        }

        File fileUpload = localFileUploadUtils.uploadDempFile(file, fileName);
        // 获取导入的数据
        List<Map<String, Object>> dataMapList = null;
        try {
            dataMapList = myExcelUtils.paresExclToMapList(BusinessConstant.import_qy_gysxx_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入企业供应商信息接口出错-{}",e.getMessage());
        }
        fileUpload.delete();
        boolean flag = spcyQyInfoService.importQyGysxxByFqyid("", fqyid, dataMapList);
        if (!flag){
            return HttpResult.ok("导入失败！");
        }
        return HttpResult.ok("导入成功！");
    }

    @Log(title = "下载企业供应商信息接口-导入模板")
    @ApiOperation(value = "下载企业供应商信息接口-导入模板")
    @GetMapping("/exporyQyGysxxMb")
    public void exporyQyGysxxMb(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("exporyQyGysxxMb.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.import_qy_gysxx_XML, out);
        } catch (Exception e) {
            log.error("下载企业供应商信息接口-导入模板-错误-{}",e.getMessage());
        }
    }

    @Log(title = "导出-企业供应商信息接口")
    @ApiOperation(value = "导出-企业供应商信息接口")
    @GetMapping("/exportQyGysxx")
    public void exportQyGysxx(@RequestParam(value = "fqyid",defaultValue = "") String fqyid,
                             HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(fqyid)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("参数为空！");
            writer.close(); // 不要忘记关闭PrintWriter
            return;
        }

        try {
            String name = "exportQyGysxx";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<Object> list = new ArrayList<>(); // 导出的数据
            List<SpcyQyYlgyssj> dataList = spcyQyInfoService.selectGysxxList(fqyid);
            for (SpcyQyYlgyssj e : dataList){
                list.add(e);
            }

            myExcelUtils.outputListToExclFile(BusinessConstant.import_qy_gysxx_XML, list, out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出-企业供应商信息接口出错-{}",e.getMessage());
        }
    }

    @Log(title = "下载企业品种信息接口-导入模板")
    @ApiOperation(value = "下载企业品种信息接口-导入模板")
    @GetMapping("/exporyQyPzxxMb")
    public void exporyQyPzxxMb(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("exporyQyPzxxMb.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.import_qy_pzxx_XML, out);
        } catch (Exception e) {
            log.error("下载企业品种信息接口-导入模板-错误-{}",e.getMessage());
        }
    }

    @Log(title = "导出-企业品种信息接口")
    @ApiOperation(value = "导出-企业品种信息接口")
    @GetMapping("/exportQyPzxx")
    public void exportQyPzxx(@RequestParam(value = "fqyid",defaultValue = "") String fqyid,
                              HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(fqyid)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("参数为空！");
            writer.close(); // 不要忘记关闭PrintWriter
            return;
        }

        try {
            String name = "exportQyPzxx";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<Object> list = new ArrayList<>(); // 导出的数据
            List<SpcyQyPzjbxx> dataList = spcyQyInfoService.selectPzxxList(fqyid);
            for (SpcyQyPzjbxx e : dataList){
                list.add(e);
            }

            myExcelUtils.outputListToExclFile(BusinessConstant.import_qy_pzxx_XML, list, out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出-企业品种信息接口口出错-{}",e.getMessage());
        }
    }

    @Log(title = "导入-企业品种信息接口")
    @ApiOperation(value = "导入-企业品种信息接口")
    @PostMapping(value = "importQyPzxx")
    public HttpResult importQyPzxx(@RequestParam("file") MultipartFile file,
                                    @RequestParam(value = "fqyid",defaultValue = "") String fqyid){
        if (StringUtils.isBlank(fqyid)){
            return HttpResult.error("参数为空！");
        }

        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");
        }

        File fileUpload = localFileUploadUtils.uploadDempFile(file, fileName);
        // 获取导入的数据
        List<Map<String, Object>> dataMapList = null;
        try {
            dataMapList = myExcelUtils.paresExclToMapList(BusinessConstant.import_qy_pzxx_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入企业品种信息接口出错-{}",e.getMessage());
        }
        fileUpload.delete();
        boolean flag = spcyQyInfoService.importQyPzxxByFqyid("", fqyid, dataMapList);
        if (!flag){
            return HttpResult.ok("导入失败！");
        }
        return HttpResult.ok("导入成功！");
    }

}
